<?php

class Addcontroller extends CI_Controller{

   public function __construct(){
          parent::__construct();
          $this->load->library('session');

   }  

   public function index()
	{
        //check if user is logged in, if not load login form
            $this->load->view('adds/index');
       
        
	}

   

    public function logon(){

        $response="";
        try{
            $data = json_decode(file_get_contents('php://input'));
            $user =$data->username;
            $pass = $data->password;
            if($user=='john' && $pass=='cdefgabc'){
                $this->set_session_data('username',$user);
                 $response='0';
            }else{
                $response="1";
            }
        }catch(Exception $e){
           $response = $e->getMessage();
        }
       

        $this->output->set_content_type('application/json');
        
        $this->output->set_output(json_encode($response));
        //echo utf8_encode($response);
        
       
    }

    public function showAddTypes(){
        $this->load->model("dbmanager","dbmanager");
        $adtypes = $this->dbmanager->get_ad_types();
        $this->output->set_content_type('application/json');
        
        $this->output->set_output(json_encode($adtypes));
       // $this->output->set_output(json_encode(array('dispadd'=>'Display Advertising','cladd'=>'Classified Advertising','obt'=>'Obituary')));

    }

    private function get_session_data($key){
        $data = $this->session->userdata($key);
        return $data;
    }

    private function set_session_data($key,$value){
        $this->session->set_userdata($key,$value);
    }

    private function does_session_key_exists($key){
        if(!isset($_SESSION[$key])){
           return false;
        }else{
           return true;
        }
    }

    public function showTypeCategories($type){
        $this->load->model("dbmanager","dbmanager");
        $this->set_session_data('adtype',$type);
        $typeCatList = $this->dbmanager->get_categories_by_type($type);
        
        $this->output->set_content_type('application/json');
        $this->output->set_output(json_encode($typeCatList));
    }

    public function showCatItems($category,$type){
        $this->load->model("dbmanager","dbmanager");
        $this->set_session_data('category',$category);
        $catItemList = $this->dbmanager->get_products_by_type_category($category,$type);
        $this->output->set_content_type('application/json');
        $this->output->set_output(json_encode($catItemList));

    }

     public function showCatetorySizes($category){
        $catSizeList=array();
        if($category=="cat-0001"){
          $catSizeList = array('cols'=>'9','rows'=>'53');
        }

       

        $this->output->set_content_type('application/json');
        $this->output->set_output(json_encode($catSizeList));

    }

    public function uploadFiles(){
        $message='';
        $allowedExts = array("gif", "jpeg", "jpg", "png");
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);
        if ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg")|| ($_FILES["file"]["type"] == "image/x-png")
        || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"] < 100000) && in_array($extension, $allowedExts)){
          if ($_FILES["file"]["error"] > 0)
            {
              $message+= "Return Code: " . $_FILES["file"]["error"] . "<br>";
            }
          else
            {
           $message+= "Upload: " . $_FILES["file"]["name"] . "<br>";
           $message+= "Type: " . $_FILES["file"]["type"] . "<br>";
           $message+= "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
           $message+= "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

            if (file_exists("upload/" . $_FILES["file"]["name"]))
              {
                 $message+= $_FILES["file"]["name"] . " already exists. ";
              }
            else
              {
              move_uploaded_file($_FILES["file"]["tmp_name"],
              "upload/" . $_FILES["file"]["name"]);
               $message+= "Stored in: " . "upload/" . $_FILES["file"]["name"];
              }
            }
          }
        else
          {
          $message= "Invalid file";
          }

        $this->output->set_content_type('application/json');
        $this->output->set_output(json_encode(message));
    }

   


    public function showAdDetails(){
        //
        //get the prices for each product
        //$products = 'philstar';
        $products = $_REQUEST['products'];
        $sdate = $_REQUEST['sdate'];
        $edate = $_REQUEST['edate'];
        $type = $_REQUEST['type'];
        $title = $_REQUEST['title'];
        $desc = $_REQUEST['desc'];
        $col = $_REQUEST['col'];
        $row = $_REQUEST['row'];
        $cat = $_REQUEST['cat'];

        
        $prods = explode('_',$products);
        $ads_days=0;
        $wkday_price=0;
        $wkend_price=0;
        $prod_name="";
        //load products mobel
        $this->load->model("dbmanager","dbmanager");
        //$products = $this->products->get_all_products();
        $html="";
       //if($cat=='cat-0001'){
            //need to check date if it falls on a weekday or weekend 
            //need also to check number of days
             $ads_days = $this->numOfDays($sdate,$edate);
             $days=0;
             $totCost=0;
             $grandTotal=0;
             $prodPrice=0;
             $cart_data=array();
             $cartid=0;
             $type_desc="";
             
            if($type=='t-0001') $type_desc = 'Display Ads';
            if($type=='t-0002') $type_desc = 'Classified Ads';
            if($type=='t-0003') $type_desc = 'Obituary Ads';

             foreach($prods as $p){
                 
                 $cur_day = date("Y-m-d",strtotime($sdate));
                 $prod_details = $this->dbmanager->get_product_details($type,$p);
                
                 foreach($prod_details as $r){
                      $wkday_price = $r['wkday_price'];
                      $wkend_price =$r['wkend_price'];
                      $prod_name = $r['name'];
                 }
                 
                



                 $html.= "<div data-role=collapsible-set>";
                
                 $html.= "<div id='" . $p . "' data-role=collapsible data-theme='b' data-content-theme='b' data-mini='true'>";   
                 $html.= "<h1>" . $prod_name   ."</h1>";
                 $days=0;

                 $html.= "<p><b>Running Dates:</b><br/>From " . $sdate ." To " . $edate . "<br/>";
                 $html.= "<b>Duration:</b>" . ($ads_days + 1) . " Day(s)<br/>";

                 $html.= "<b>Ad Size:</b> ". $col ."x" . $row ." cm <br/>";
                 $html.= "<b>Weekday Price:</b> Php ".  $wkday_price ."  <br/>";
                 $html.= "<b>Weekend Price:</b> Php ".  $wkend_price ."  </p>";

                  
                
                 $html.= "<div class='ui-grid-b'>";
                 $html.= "<div class='ui-block-a'><b> Date</b></div>";
                 $html.= "<div class='ui-block-b'><b> Price</b></div>";
                 $html.= "<div class='ui-block-c'><b> Total</b></div>";



                 while($days <=$ads_days){
                     //get the prod price given type
                     //price is diff from wkday and wkends
                     $isWkend =$this->isWeekend($cur_day);
                     
                          
                         if($isWkend==0){
                            $html.="<div class='ui-block-a'>" . $cur_day . "</div>" ;
                            $html.="<div class='ui-block-b'> Php " . $wkday_price . "</div>" ;
                            $html.="<div class='ui-block-c'> Php " . ($col * $row * $wkday_price) . "</div>" ;
                            $prodPrice = $wkday_price;
                            $totCost=$totCost+ ($col * $row * $wkday_price);
                         }else{
                             $html.="<div class='ui-block-a'>" . $cur_day . "</div>" ;
                             $html.="<div class='ui-block-b'> Php " . $wkend_price . "</div>" ;
                             $html.="<div class='ui-block-c'> Php " . ($col * $row * $wkend_price) . "</div>" ;
                             $prodPrice = $wkend_price;
                             $totCost= $totCost + ($col * $row * $wkend_price);
                         }
                           

                    
                         $cur_day = $this->nextDay($cur_day);
                         $days++;
   
                     }
                   
                  $html.="</div>";//end of grid
                  $grandTotal = $grandTotal + $totCost;
                  $html.="<p> Total Cost= Php " . $totCost;
                  $html.="</div>";
                  
                  //insert into AdCart table
                   $fileDir = 'upload/' . date('Y-m-d') . "/". $this->get_session_data('session_id') . "/". $this->get_session_data('adtype')."/". $this->get_session_data('category') ;
       
                  $cart_data['typeid'] = $type;
                  $cart_data['prodid'] = $p;
                  $cart_data['userid'] = "test_user";
                  $cart_data['sessionid'] = "test_user";
                  $cart_data['total'] = $totCost;
                  $cart_data['adsize'] = $col . " X " . $row;
                  $cart_data['from_date'] = $sdate;
                  $cart_data['to_date'] = $edate;
                  $cart_data['adfile'] = $fileDir;
                  $cart_data['adtitle'] = $title;
                  $cart_data['addesc'] = $desc;

                  $this->dbmanager->add_to_cart($cart_data);
                  
                  $totCost=0;
                  
                  $html.="</div>"; //end of collapsible-set
                 
                
             }
             $html.="<input type='hidden' name='cartid' value='{$cartid}'/>";
             $html.="<p> Grand Total =Php " . $grandTotal;
                  
             echo utf8_encode($html);
           
       // }

        //$this->output->set_content_type('application/json');
        //$this->output->set_output(json_encode($products));
    }

    public function addToCart(){
              // 
         //generate a new cart if there is not cart in session
        $this->load->model("dbmanager","dbmanager");
        $cartid=$this->get_session_data('cartid');
        if($cartid==null){
            $cartid = $this->dbmanager->get_next_cartid();
            $this->set_session_data('cartid',$cartid);
        }

         //$cartid=$this->get_session_data('cartid');
       

        //get the prices for each product
        //$products = 'philstar';
        $products = $_REQUEST['products'];
        $sdate = $_REQUEST['sdate'];
        $edate = $_REQUEST['edate'];
        $type = $_REQUEST['type'];
        $title = $_REQUEST['title'];
        $desc = $_REQUEST['desc'];
        $col = $_REQUEST['col'];
        $row = $_REQUEST['row'];
        $cat = $_REQUEST['cat'];
        $user = $this->get_session_data('username');
        $sessionid = $this->get_session_data('session_id');

        /* $products = "p-00001_p-00002_p-00003";
        $sdate = date('Y-m-d');
        $edate = date('Y-m-d');
        $type = 't-0001';
        $title = 'Test Title';
        $desc = 'Test  desc';
        $col = '3';
        $row = '8';
        $cat = 'cat-0001';
        $user = 'test_user';
        $sessionid = 'test';*/



         //load products mobel
        
        $prods = explode('_',$products);
        $ads_days=0;
        $wkday_price=0;
        $wkend_price=0;
        $prod_name="";
        $html="";
        $ads_days = $this->numOfDays($sdate,$edate);
        $days=0;
        $totCost=0;
        $grandTotal=0;
        $prodPrice=0;
        $cart_data=array();
        $type_desc="";


        
             foreach($prods as $p){
                 $cur_day = date("Y-m-d",strtotime($sdate));
                 $prod_details = $this->dbmanager->get_product_details($type,$p);
                /* echo "Product Detail for Type " . $type . " product ".$p . "<br/>";
                 foreach($prod_details as $pr){
                     foreach($pr as $k=>$v){
                         echo $k . "=" . $v . "<br/>";
                     }
                     
                 }
                 echo "AD days: " . $ads_days+1 . "<br/>";*/
                
                 foreach($prod_details as $r){
                      $wkday_price = $r['wkday_price'];
                      $wkend_price =$r['wkend_price'];
                      $prod_name = $r['name'];
                 }
                 
                 while($days <=$ads_days){
                     //get the prod price given type
                     //price is diff from wkday and wkends
                     $isWkend =$this->isWeekend($cur_day);
                         if($isWkend==0){
                            $prodPrice = $wkday_price;
                            $totCost=$totCost+ ($col * $row * $wkday_price);
                            /*echo "Day is weekday" . "<br/>";;
                            echo "Price:".$wkday_price . "<br/>";;
                            echo "Cost:" . $totCost . "<br/>";;*/
                         }else{
                             $prodPrice = $wkend_price;
                             $totCost= $totCost + ($col * $row * $wkend_price);
                             /*echo "Day is weekend" . "<br/>";;
                             echo "Price:".$wkend_price . "<br/>";;
                             echo " Cost:" . $totCost . "<br/>";;*/
                         }
                           
                         $cur_day = $this->nextDay($cur_day);
                         $days++;
   
                     }
                  $grandTotal = $grandTotal + $totCost;
                  
                 // echo "Total: ".$totCost . "<br/>";;
                  
                  //insert into AdCart table
                  $fileDir = 'upload/' . date('Y-m-d') . "/". $this->get_session_data('session_id') . "/". $this->get_session_data('adtype')."/". $this->get_session_data('category') ;
                  $cart_data['cartid'] = $cartid;
                  $cart_data['typeid'] = $type;
                  $cart_data['prodid'] = $p;
                  $cart_data['userid'] = $user;
                  $cart_data['sessionid'] = $sessionid;
                  $cart_data['total'] = $totCost;
                  $cart_data['adsize'] = $col . " X " . $row;
                  $cart_data['from_date'] = $sdate;
                  $cart_data['to_date'] = $edate;
                  $cart_data['adfile'] = $fileDir;
                  $cart_data['adtitle'] = $title;
                  $cart_data['addesc'] = $desc;
                 
                 /* echo "To be added to cart";
                  foreach($cart_data as $key=>$value){
                      echo $key . " = " . $value . "<br/>";;
                  }*/
                  $this->dbmanager->add_to_cart($cart_data);
                  $days=0;
                  $totCost=0;
                 
                
             }
            
       // }
       //display cart details to user
       $this->display_cart_details();
        
    }

    public function display_cart_details(){
        //load products mobel
        $this->load->model("dbmanager","dbmanager");
        $user = $this->get_session_data('username');
        $adtypes = array('t-0001'=>'Display','t-0002'=>'Classified','t-0003'=>'Obituary');
        $html="";
        $total=0;
        $grandTotal=0;
         
             
        foreach($adtypes as $key=>$value){
            $html.= "<div data-role=collapsible-set id='cart_items'>";
        
            $html.= "<div id='" . $key . "' data-role=collapsible data-theme='b' data-content-theme='b' data-mini='true'>";   
             $html.= "<h1>" . $value   ."</h1>";

             /*$html.= "<div class='ui-grid-d'>";
             $html.= "<div class='ui-block-a'><b> Product</b></div>";
             $html.= "<div class='ui-block-b'><b> AD Size</b></div>";
             $html.= "<div class='ui-block-c'><b> AD Dates</b></div>";
             $html.= "<div class='ui-block-d'><b> Price <br/><Weekday/Weekend</b></div>";
             $html.= "<div class='ui-block-e'><b> Total</b></div>";*/

            $html.="<ul data-role='listview' data-inset='true' data-theme='a' data-icon='delete'>";

            $cart = $this->dbmanager->get_user_cart($user,$key);
            foreach($cart->result_array() as $cr){
                 
                $prod_details = $this->dbmanager->get_product_details($key,$cr['prodid']);
                $prod_name='';
                $wkday_price=0;
                $wkend_price=0;

                 foreach($prod_details as $r){
                      $wkday_price = $r['wkday_price'];
                      $wkend_price =$r['wkend_price'];
                      $prod_name = $r['name'];
                 }

                  
                  /*$html.= "<div class='ui-block-a'>". $prod_name ."</div>";
                  $html.= "<div class='ui-block-b'>". $cr['adsize'] ."</div>";
                  $html.= "<div class='ui-block-c'>". $cr['from_date'] . " to " . $cr['to_date'] . "</div>";
                  $html.= "<div class='ui-block-d'>". $wkday_price . "/" . $wkend_price . "</div>";
                  $html.= "<div class='ui-block-e'> Php ". $cr['total'] . "</div>";
                  $grandTotal =  $grandTotal + $cr['total'];*/
                 

                  $html.="<li data-name='" . $cr['prodid']."_". $key ."_". $user ."'><a href='#'>";
                  $html.="<h1>" . $prod_name . "</h1>";
                  $html.="<p>AD Size: ". $cr['adsize'] . "<br/>";
                  $html.="AD Dates: ".$cr['from_date'] . " to " . $cr['to_date']  . "<br/>";
                  $html.="Weekday Price: ".$wkday_price . " <br/> " . "Weekend Price: " . $wkend_price  . "<br/>";
                  $html.="Total: Php " . $cr['total'] . "</p>";
                  $html.="</a></li>";
                  $grandTotal =  $grandTotal + $cr['total'];
             
            }
           //$html.="</div>";
           $html.="</ul>";
           $html.="</div>";//end of collapsible set
        }
        $html.="<h2>Grand Total:Php {$grandTotal}</h2>";
        
        echo utf8_encode($html);

    }

    public function deleteItemFromCart(){
         //load products mobel
        $this->load->model("dbmanager","dbmanager");

        $typeid = $_REQUEST['typeid'];
        $userid = $_REQUEST['userid'];
        $prodid = $_REQUEST['prodid'];

        $this->dbmanager->delete_item_from_cart($prodid,$typeid,$userid);

        //reload cart
        $this->display_cart_details();




    }

    public function isWeekend($date){
        return (date('N',strtotime($date))>=6);
    }

    public function numOfDays($sdate,$edate){
        $start = strtotime($sdate);
        $end = strtotime($edate);

        $days_between = ceil(abs($end-$start)/86400);
        //$days_between = ($end-$start)/(60*60*24);
        return $days_between;
    }

    public function nextDay($date){
        return date('Y-m-d',strtotime($date. ' + 1 day'));
    }

    public function showAdTypes(){
        $this->load->model("dbmanager","dbmanager");
        $this->dbmanager->get_adtypes();
    }

    public function showNextCartID(){
        try{
            $this->load->model("dbmanager","dbmanager");
        $cartid = $this->dbmanager->get_next_cartid();
        echo $cartid;
            
        }catch(Exception $e){
            echo $e;
        }
        
    }



    public function upload(){
        //$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        $targetDir = 'upload/' . date('Y-m-d') . "/" . $this->get_session_data('session_id') . "/". $this->get_session_data('adtype')."/". $this->get_session_data('category') ;
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds




        // Create target dir
        if (!file_exists($targetDir)) {
	        @mkdir($targetDir,0,true);
        }

        // Get a file name
        if (isset($_REQUEST["name"])) {
	        $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
	        $fileName = $_FILES["file"]["name"];
        } else {
	        $fileName = uniqid("file_");
        }

        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;


        // Remove old temp files	
        if ($cleanupTargetDir) {
	        if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
		        die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
	        }

	        while (($file = readdir($dir)) !== false) {
		        $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

		        // If temp file is current file proceed to the next
		        if ($tmpfilePath == "{$filePath}.part") {
			        continue;
		        }

		        // Remove temp file if it is older than the max age and is not the current file
		        if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
			        @unlink($tmpfilePath);
		        }
	        }
	        closedir($dir);
        }	


        // Open temp file
        if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
	        die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
	        if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
		        die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
	        }

	        // Read binary input stream and append it to temp file
	        if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
		        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
	        }
        } else {	
	        if (!$in = @fopen("php://input", "rb")) {
		        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
	        }
        }

        while ($buff = fread($in, 4096)) {
	        fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        // Check if file has been uploaded
        if (!$chunks || $chunk == $chunks - 1) {
	        // Strip the temp .part suffix off 
	        rename("{$filePath}.part", $filePath);
        }

        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');

            }
    
}
?>

